<script setup lang="ts">
import { ref, reactive, onMounted, h } from 'vue';
import { NButton, NCard, NSpace, NDataTable, NPopconfirm, NTag, useMessage } from 'naive-ui';
import { executeQuery, fetchQueryHistoryList, deleteQueryHistory, reExecuteHistory } from '@/service/api';
import SqlEditorModal from './modules/sql-editor-modal.vue';
import QueryResultDrawer from './modules/query-result-drawer.vue';
import QueryHistoryDrawer from './modules/query-history-drawer.vue';

defineOptions({
  name: 'DataPlatformQuery'
});

const message = useMessage();

const loading = ref(false);
const queryHistoryList = ref<Api.DataPlatform.QueryHistory[]>([]);
const pagination = reactive({
  page: 1,
  pageSize: 10,
  itemCount: 0,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100]
});

// 模态框和抽屉状态
const sqlEditorModalRef = ref<InstanceType<typeof SqlEditorModal>>();
const queryResultDrawerRef = ref<InstanceType<typeof QueryResultDrawer>>();
const queryHistoryDrawerRef = ref<InstanceType<typeof QueryHistoryDrawer>>();

// 表格列定义
const columns = [
  {
    title: '查询名称',
    key: 'queryName',
    width: 200,
    ellipsis: { tooltip: true }
  },
  {
    title: '查询类型',
    key: 'queryType',
    width: 100,
    render: (row: Api.DataPlatform.QueryHistory) => {
      const typeMap: Record<string, { label: string; type: 'info' | 'success' }> = {
        SQL: { label: 'SQL查询', type: 'info' },
        VISUAL: { label: '可视化查询', type: 'success' }
      };
      const config = typeMap[row.queryType] || { label: row.queryType, type: 'info' };
      return h(NTag, { type: config.type }, () => config.label);
    }
  },
  {
    title: 'SQL内容',
    key: 'sqlContent',
    width: 300,
    ellipsis: { tooltip: true }
  },
  {
    title: '数据源',
    key: 'datasourceName',
    width: 150
  },
  {
    title: '执行时间',
    key: 'executionTime',
    width: 120,
    render: (row: Api.DataPlatform.QueryHistory) => {
      return row.executionTime ? `${row.executionTime}ms` : '-';
    }
  },
  {
    title: '结果行数',
    key: 'resultCount',
    width: 100
  },
  {
    title: '状态',
    key: 'status',
    width: 100,
    render: (row: Api.DataPlatform.QueryHistory) => {
      const statusMap: Record<string, { label: string; type: 'success' | 'error' }> = {
        SUCCESS: { label: '成功', type: 'success' },
        FAILED: { label: '失败', type: 'error' }
      };
      const config = statusMap[row.status] || { label: row.status, type: 'error' };
      return h(NTag, { type: config.type }, () => config.label);
    }
  },
  {
    title: '创建时间',
    key: 'createTime',
    width: 180
  },
  {
    title: '操作',
    key: 'actions',
    width: 200,
    fixed: 'right' as const,
    render: (row: Api.DataPlatform.QueryHistory) => {
      return h(NSpace, {}, () => [
        h(NButton, { 
          size: 'small', 
          onClick: () => handleViewDetail(row.id) 
        }, () => '详情'),
        h(NButton, { 
          size: 'small', 
          type: 'primary', 
          onClick: () => handleReExecute(row.id) 
        }, () => '重新执行'),
        h(NPopconfirm, { 
          onPositiveClick: () => handleDelete(row.id) 
        }, {
          default: () => '确认删除此查询历史吗?',
          trigger: () => h(NButton, { 
            size: 'small', 
            type: 'error' 
          }, () => '删除')
        })
      ]);
    }
  }
];

// 加载历史记录列表
async function loadHistoryList() {
  loading.value = true;
  try {
    const { data } = await fetchQueryHistoryList({
      pageNum: pagination.page,
      pageSize: pagination.pageSize
    });
    if (data) {
      queryHistoryList.value = data.rows;
      pagination.itemCount = data.total;
    }
  } catch (error) {
    message.error('加载查询历史失败');
  } finally {
    loading.value = false;
  }
}

// 打开SQL编辑器
function handleNewQuery() {
  sqlEditorModalRef.value?.open();
}

// 查看详情
function handleViewDetail(id: number) {
  queryHistoryDrawerRef.value?.open(id);
}

// 重新执行
async function handleReExecute(id: number) {
  loading.value = true;
  try {
    const { data } = await reExecuteHistory(id);
    if (data) {
      message.success('查询执行成功');
      queryResultDrawerRef.value?.open(data);
      await loadHistoryList();
    }
  } catch (error) {
    message.error('查询执行失败');
  } finally {
    loading.value = false;
  }
}

// 删除
async function handleDelete(id: number) {
  try {
    await deleteQueryHistory([id]);
    message.success('删除成功');
    await loadHistoryList();
  } catch (error) {
    message.error('删除失败');
  }
}

// 分页变化
function handlePageChange(page: number) {
  pagination.page = page;
  loadHistoryList();
}

function handlePageSizeChange(pageSize: number) {
  pagination.pageSize = pageSize;
  pagination.page = 1;
  loadHistoryList();
}

// SQL编辑器执行成功回调
async function handleQuerySuccess(result: Api.DataPlatform.QueryResultDTO) {
  queryResultDrawerRef.value?.open(result);
  await loadHistoryList();
}

onMounted(() => {
  loadHistoryList();
});
</script>

<template>
  <div class="h-full flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <NCard title="数据查询" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <NButton type="primary" @click="handleNewQuery">
          <icon-ic-round-plus class="mr-4px text-20px" />
          新建查询
        </NButton>
      </template>

      <div class="h-full flex-col">
        <NDataTable
          :columns="columns"
          :data="queryHistoryList"
          :loading="loading"
          :pagination="pagination"
          :scroll-x="1400"
          :flex-height="true"
          class="sm:h-full"
          @update:page="handlePageChange"
          @update:page-size="handlePageSizeChange"
        />
      </div>
    </NCard>

    <!-- SQL编辑器模态框 -->
    <SqlEditorModal ref="sqlEditorModalRef" @success="handleQuerySuccess" />

    <!-- 查询结果抽屉 -->
    <QueryResultDrawer ref="queryResultDrawerRef" />

    <!-- 查询历史详情抽屉 -->
    <QueryHistoryDrawer ref="queryHistoryDrawerRef" />
  </div>
</template>

<style scoped></style>
